#include "BlockQueue.hpp"
#include <pthread.h>
#include <ctime>
#include <unistd.h>

#include "Task.hpp"

std::string oper = "+-*/%";
struct ThreadData
{
    BlockQueue<Task>* bq;
    std::string threadname;
};
void *Productor(void *args)
{
   ThreadData *td = static_cast<ThreadData *>(args);
    // 有了阻塞队列
    //  进行生产
    //  模拟生产者生产数字
    
    while (true)
    {
        int data1 = rand() % 10 + 1;
        int data2 = rand() % 10;
        Task t = Task(data1, data2, oper[rand() % oper.size()]);
        td->bq->Push(t);
        cout << "生产了一个任务：" << t.ShowTask() << " who :"<< td->threadname << endl;
        // sleep(1);
    }
    return nullptr;
}
void *Consumer(void *args)
{
    ThreadData *td = static_cast<ThreadData *>(args);
    while (true)
    {
        Task t = td->bq->Pop();
        t();
        cout << "消费了一个任务：" << t.Result() <<" who :"<< td->threadname << endl;
        sleep(1);
    }
    return nullptr;
}
int main()
{
    srand(time(nullptr));
    BlockQueue<Task> *bq = new BlockQueue<Task>();

    pthread_t p[3];
    pthread_t c[5];
    for (int i = 0; i < 1; ++i)
    {
        ThreadData* td = new ThreadData();
        td->bq = bq;
        td->threadname = "Productor - " + std::to_string(i+1); 
        pthread_create(p + i, nullptr, Productor, td);
    }
    for (int i = 0; i < 1; ++i)
    {
        ThreadData* td = new ThreadData();
        td->bq = bq;
        td->threadname = "consumer - " + std::to_string(i+1);
        pthread_create(c + i, nullptr, Consumer, td);
    }
    for (int i = 0; i < 1; ++i)
    {
        pthread_join(p[i], nullptr);
    }

    for (int i = 0; i < 1; ++i)
    {
        pthread_join(c[i], nullptr);
    }
    delete bq;
    return 0;
}